package his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import his.entity.CaseNumber;
import his.entity.Patient;
import his.entity.Userid;
import his.persistence.PatientMapper;
import his.service.PatientService;
import org.example.his.common.api.CommonResponse;
import org.example.his.common.api.RequestUtils;
import org.example.his.common.auth.JwtAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Queue;

@Service
public class PatientServiceImpl implements PatientService {

    @Autowired
    PatientMapper patientMapper;


    @Override
    public CommonResponse<String> get_realname(String casenumber) {

        QueryWrapper<Patient> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("CaseNumber",casenumber);
        Patient patient=patientMapper.selectOne(queryWrapper1);
        if(patient!=null){
            return CommonResponse.createForSuccess(patient.getRealName());
        }else{
            return CommonResponse.createForError("搜索失败");
        }

    }

    @Override
    public CommonResponse<Patient> get_patient_info(String token) {

        QueryWrapper<Patient> queryWrapper=new QueryWrapper<>();
        if(JwtAuth.checkToken(token)){
            String openid=JwtAuth.jwtDecrypt(token);
            queryWrapper.eq("OpenID",openid);
            Patient patient=patientMapper.selectOne(queryWrapper);

            return CommonResponse.createForSuccess(patient);
        }else{
            return CommonResponse.createForError("token无效！");
        }

    }

    @Override
    public CommonResponse<String> producce_token(String code) {

        String openid = null;
        String token=null;
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+"wx9403d9d21cd5e2b1"+"&secret="+"0d510b05f526e653644e8053d8383a15"+"&js_code="+code+"&grant_type=authorization_code";
        System.out.println(url);
        try {
            ObjectMapper objectMapper=new ObjectMapper();
            Userid userid=objectMapper.readValue(RequestUtils.sendGet(url,null),Userid.class);
            openid=userid.getOpenid();
            System.out.println(userid.getOpenid());
            token=JwtAuth.jwtEncipher(openid,openid);

        } catch (IOException e) {
            e.printStackTrace();
        }

        QueryWrapper<Patient> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("OpenID",openid);
        Patient patient1=patientMapper.selectOne(queryWrapper1);
        if(patient1!=null){
            System.out.println("已存在");
            return CommonResponse.createForSuccess(token);
        }else{
            Patient patient=new Patient();
            patient.setOpenID(openid);

            QueryWrapper<Patient> queryWrapper2=new QueryWrapper<>();
            List<Patient> patientList1 = patientMapper.selectList(queryWrapper2);
            //设置为最小值 方便之后更新
            int maxCaseNumber = Integer.MIN_VALUE;
            for (int i=0;i<patientList1.size();i++) {
                int CaseNumberInt = Integer.parseInt(patientList1.get(i).getCaseNumber());
                if (CaseNumberInt > maxCaseNumber) {
                    maxCaseNumber = CaseNumberInt;
                }
            }

            patient.setCaseNumber(String.valueOf(maxCaseNumber+1));
            patientMapper.insert(patient);
            return CommonResponse.createForSuccess(token);
        }

    }

    @Override
    public CommonResponse add_patient(String token, String realname, int gender, String idnumber, String birthdate, int age, String agetype, String homeaddress) {

        if(JwtAuth.checkToken(token)){
            String openid=JwtAuth.jwtDecrypt(token);
            QueryWrapper<Patient> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.eq("OpenID",openid);
            List<Patient> patientList1=patientMapper.selectList(queryWrapper1);
            Patient patient=new Patient();

            patient.setRealName(realname);
            patient.setGender(gender);
            patient.setIDnumber(idnumber);

            patient.setBirthDate(birthdate);
            patient.setAge(age);
            patient.setAgeType(agetype);
            patient.setHomeAddress(homeaddress);
            patientMapper.update(patient,queryWrapper1);
            return CommonResponse.createForSuccess("新增成功");

        }else{
            return CommonResponse.createForError("token无效！");
        }


    }


    public static Date parseDateTimeString(String dateTimeString, String pattern) {
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern);
        try {
            // 将字符串解析为日期
            Date parsedDateTime = dateTimeFormat.parse(dateTimeString);
            return parsedDateTime;
        } catch (ParseException e) {
            // 解析失败，处理异常情况
            e.printStackTrace();
            return null;
        }
    }
}
